package nc.impl.jzfdc.pub;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.logging.Logger;
import nc.bs.ml.NCLangResOnserver;
import nc.bs.trade.business.HYSuperDMO;
import nc.bs.trade.comchkref.CheckRef;
import nc.itf.jzfdc.pub.IJZFDCPubBusi;
import nc.jdbc.framework.JdbcSession;
import nc.jdbc.framework.PersistenceManager;
import nc.jdbc.framework.exception.DbException;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.uif.pub.exception.UifException;
import nc.vo.ml.AbstractNCLangRes;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.trade.pub.IExAggVO;

public class JZFDCPubBusiImpl
  implements IJZFDCPubBusi
{
  public void deleteArray(SuperVO[] vos)
    throws BusinessException
  {
    try
    {
      HYSuperDMO dmo = new HYSuperDMO();
      dmo.deleteArray(vos);
    }
    catch (Exception e) {
      Logger.error(e.getMessage(), e);
      throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("H0", "UPPH10301-001915") + e.getMessage());
    }
  }

  public Vector executeQuerySQL(String sql) throws BusinessException
  {
    try
    {
      HYSuperDMO dmo = new HYSuperDMO();
      return dmo.executeQuerySQL(sql);
    } catch (Exception e) {
      throw new BusinessException("JZFDCPubBusiImpl::executeQuerySQL(String sql) Exception!", e);
    }
  }

  public int executeUpdateSQL(String sql) throws BusinessException
  {
    try
    {
      HYSuperDMO dmo = new HYSuperDMO();
      return dmo.executeUpdateSQL(sql);
    } catch (Exception e) {
      throw new BusinessException("JZPMPubBusiImpl::executeUpdateSQL(String sql) Exception!", e);
    }
  }

  public SuperVO[] queryByClause(Class cl, String condtionStr, String orderStr)
    throws BusinessException
  {
    SuperVO[] vos = null;
    try
    {
      Collection col = new BaseDAO().retrieveByClause(cl, condtionStr, orderStr);
      if (col.size() > 0)
        vos = (SuperVO[])(SuperVO[])col.toArray((SuperVO[])(SuperVO[])Array.newInstance(cl, 0));
    } catch (Exception e) {
      throw new BusinessException(e.getMessage());
    }
    return vos;
  }

  public SuperVO[] queryByCondition(Class voClass, String strWhere, String strOrderBy, String[] selectedFields)
    throws BusinessException
  {
    SuperVO[] vo = null;
    try {
      HYSuperDMO dmo = new HYSuperDMO();

      if ((strWhere != null) && (strWhere.length() != 0))
        strWhere = " (isnull(dr,0)=0) and " + strWhere;
      else {
        strWhere = "isnull(dr,0)=0";
      }
      vo = dmo.queryByWhereClause(voClass, strWhere, strOrderBy, selectedFields);
    } catch (DAOException de) {
      Logger.error(de.getMessage(), de);
      throw new UifException(NCLangResOnserver.getInstance().getStrByID("uifactory", "UPPuifactory-000006"), de);
    } catch (Exception e) {
      Logger.error(e.getMessage(), e);
      throw new BusinessException(NCLangResOnserver.getInstance().getStrByID("uifactory", "UPPuifactory-000005"), e);
    }
    return vo;
  }

  public SuperVO queryByPrimaryKey(Class clsName, String pk)
    throws BusinessException
  {
    SuperVO vo = null;
    try {
      Object o = new BaseDAO().retrieveByPK(clsName, pk);
      if (o != null)
        vo = (SuperVO)o;
    }
    catch (Exception e) {
      throw new BusinessException(e.getMessage());
    }
    return vo;
  }

  public SuperVO queryByPrimaryKey(Class clsName, String pk, String[] flds)
    throws BusinessException
  {
    SuperVO vo = null;
    try
    {
      Object o = new BaseDAO().retrieveByPK(clsName, pk, flds);
      if (o != null)
        vo = (SuperVO)o;
    }
    catch (Exception e) {
      throw new BusinessException(e.getMessage());
    }
    return vo;
  }

  public Object[] findFieldValue(String tablename, String pkFiled, String sFieldWanted, String[] sPks) throws BusinessException
  {
    PersistenceManager man = null;
    Object[] result = null;
    try {
//      int i;
      man = PersistenceManager.getInstance();
      JdbcSession session = man.getJdbcSession();

      StringBuffer inSql = new StringBuffer("");
      if ((sPks == null) || (sPks.length == 0)) {
        throw new BusinessException("sPks can't be null");
      }
      for (int i = 0; i < sPks.length; ++i) {
        inSql.append("'");
        inSql.append(sPks[i]);
        inSql.append("'");
        if (i != sPks.length - 1) {
          inSql.append(",");
        }
      }
      String sql = "select " + sFieldWanted + " from " + tablename + " where " + pkFiled + " in (" + inSql.toString() + ") and isnull(dr,0)=0";

      Object[] objs = ((ArrayList)session.executeQuery(sql, new ArrayListProcessor())).toArray();

      if ((objs == null) || (objs.length <= 0)) {
        Object[] arrayOfObject1 = objs;
        return arrayOfObject1;
      }
      result = new Object[objs.length];
      for (int i = 0; i < objs.length; ++i) {
        result[i] = ((Object[])(Object[])objs[i])[0];
      }

    }
    catch (DbException e)
    {
      Logger.error(e.getMessage(), e);
    } finally {
      man.release();
    }

    return result;
  }

  public Object[] findFieldValue(String tablename, String sFieldWanted, String strWhere)
    throws BusinessException
  {
    PersistenceManager man = null;
    Object[] result = null;
    try {
//      int i;
      man = PersistenceManager.getInstance();
      JdbcSession session = man.getJdbcSession();

      String sql = "select " + sFieldWanted + " from " + tablename + " where isnull(dr,0)=0";
      if ((strWhere != null) && (strWhere.length() > 0)) {
        sql = sql + " and " + strWhere;
      }
      Object[] objs = ((ArrayList)session.executeQuery(sql, new ArrayListProcessor())).toArray();

      if ((objs == null) || (objs.length <= 0)) {
        Object[] arrayOfObject1 = objs;
        return arrayOfObject1;
      }
      result = new Object[objs.length];
      for (int i = 0; i < objs.length; ++i)
        result[i] = ((Object[])(Object[])objs[i])[0];
    }
    catch (DbException e)
    {
      Logger.error(e.getMessage(), e);
    } finally {
      man.release();
    }
    return result;
  }

  public boolean isBeRefrenced(SuperVO[] vos, String key, String showName, boolean ischeckUpdate)
    throws BusinessException
  {
    try
    {
      CheckRef checkRef = new CheckRef();
      return checkRef.isBeRefrenced(vos, key, showName, ischeckUpdate);
    } catch (BusinessException e) {
      throw e;
    } catch (Exception e) {
      throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("H0", "UPPH0-002150"), e);
    }
  }

  public boolean isBeRefrenced(SuperVO vo)
    throws BusinessException
  {
    try
    {
      CheckRef check = new CheckRef();
      check.isBeRefrenced(vo);
    } catch (BusinessException e) {
      throw e;
    } catch (Exception e) {
      throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("H0", "UPPH0-002150"), e);
    }
    return false;
  }

  public AggregatedValueObject[] queryBillVOByCondition(String[] cls, String[] strWhere, String[][] flds)
    throws BusinessException
  {
    AggregatedValueObject[] vos = null;
    try
    {
      int len1 = (cls == null) ? 0 : cls.length;
      int len2 = (strWhere == null) ? 0 : strWhere.length;
      int len3 = (flds == null) ? 0 : flds.length;

      if ((len1 != len2) && (len1 != len3))
      {
        throw new UifException(NCLangRes4VoTransl.getNCLangRes().getStrByID("H0", "UPPH10301-001916"));
      }

      Class AggCls = Class.forName(cls[0]);
      Class parentCls = Class.forName(cls[1]);
      HYSuperDMO dmo = new HYSuperDMO();

      SuperVO[] parentVOs = dmo.queryByWhereClause(parentCls, strWhere[1], flds[1]);

      if ((parentVOs == null) || (parentVOs.length == 0)) {
        return null;
      }
      HashMap billHash = new HashMap();
      for (int i = 0; i < parentVOs.length; ++i)
      {
        AggregatedValueObject aggVO = (AggregatedValueObject)AggCls.newInstance();
        aggVO.setParentVO(parentVOs[i]);
        billHash.put(parentVOs[i].getPrimaryKey(), aggVO);
      }

      boolean bisIExAggVO = false;
      if (AggCls.newInstance() instanceof IExAggVO) {
        bisIExAggVO = true;
      }

      for (int j = 2; j < cls.length; ++j)
      {
        ArrayList al;
        Class itemCls = Class.forName(cls[j]);
        SuperVO item = (SuperVO)Class.forName(cls[j]).newInstance();
        String key = item.getParentPKFieldName();

        if ((key == null) || (key.trim().equals("")))
        {
          throw new UifException(NCLangResOnserver.getInstance().getStrByID("uifactory", "UPPuifactory-000500", null, new String[] { cls[j] }));
        }

        String whereStr = "(";
        for (int i = 0; i < parentVOs.length; ++i)
        {
          if (i > 0)
            whereStr = whereStr + "or ";
          whereStr = whereStr + key + " = '" + parentVOs[i].getPrimaryKey() + "'";
        }
        whereStr = whereStr + ")";
        if ((strWhere[j] != null) && (strWhere.length > 0)) {
          whereStr = whereStr + " and " + strWhere[j];
        }

        SuperVO[] items = dmo.queryByWhereClause(itemCls, whereStr, flds[j]);

        if (items == null) continue; if (items.length == 0) {
          continue;
        }

        HashMap hash = new HashMap();
        for (int i = 0; i < items.length; ++i)
        {
          String parentKey = items[i].getAttributeValue(key).toString();
          if (hash.containsKey(parentKey))
          {
            al = (ArrayList)hash.get(parentKey);
            al.add(items[i]);
          }
          else
          {
            al = new ArrayList();
            al.add(items[i]);
            hash.put(parentKey, al);
          }
        }

        for (int i = 0; i < parentVOs.length; ++i)
        {
          if (!(hash.containsKey(parentVOs[i].getPrimaryKey())))
            continue;
          AggregatedValueObject bill = (AggregatedValueObject)billHash.get(parentVOs[i].getPrimaryKey());

          al = (ArrayList)hash.get(parentVOs[i].getPrimaryKey());
          SuperVO[] children = (SuperVO[])(SuperVO[])Array.newInstance(itemCls, al.size());
          al.toArray(children);
          if (bisIExAggVO)
          {
            ((IExAggVO)bill).setTableVO(item.getTableName(), children);
          }
          else {
            bill.setChildrenVO(children);
          }
        }

      }

      vos = (AggregatedValueObject[])(AggregatedValueObject[])Array.newInstance(AggCls, parentVOs.length);

      for (int i = 0; i < parentVOs.length; ++i)
      {
        if (!(billHash.containsKey(parentVOs[i].getPrimaryKey())))
          continue;
        vos[i] = ((AggregatedValueObject)billHash.get(parentVOs[i].getPrimaryKey()));
      }

    }
    catch (Exception e)
    {
      Logger.error(e.getMessage(), e);
      throw new UifException(NCLangResOnserver.getInstance().getStrByID("uifactory", "UPPuifactory-000008"), e);
    }

    return vos;
  }

  public HashMap<String, ArrayList<String>> queryPKsMappingData(HashMap<String, Class> refVOMap, HashMap<String, ArrayList<String>> fldPKValMap, HashMap<String, String> refTablePKMap, HashMap<String, String> refTableNameMap)
    throws BusinessException
  {
    HYSuperDMO dmo = new HYSuperDMO();
    ArrayList tmpList = null;
    HashMap retMap = new HashMap();
    HashMap pkNameMap = new HashMap();
    for (String tmpFld : fldPKValMap.keySet()) {
      tmpList = (ArrayList)fldPKValMap.get(tmpFld);
      String pkFld = (String)refTablePKMap.get(tmpFld);
      String strWherePart = " (" + pkFld + " like '%";
      int i = 0; for (int n = tmpList.size(); i < n; ++i) {
        if (i == 0)
          strWherePart = strWherePart + ((String)tmpList.get(i)).replace(",", new StringBuilder().append("%' or ").append(pkFld).append(" like '%").toString());
        else
          strWherePart = strWherePart + "%' or " + pkFld + " like '%" + ((String)tmpList.get(i)).replace(",", new StringBuilder().append("%' or ").append(pkFld).append(" like '%").toString());
      }
      strWherePart = strWherePart + "%') ";
      String nameFld = (String)refTableNameMap.get(tmpFld);

      SuperVO[] superVO = dmo.queryByWhereClause((Class)refVOMap.get(tmpFld), strWherePart, new String[] { nameFld });
      for (SuperVO tmpVO : superVO) {
        if (tmpVO.getAttributeValue(nameFld) == null)
          continue;
        pkNameMap.put(tmpVO.getPrimaryKey(), tmpVO.getAttributeValue(nameFld).toString());
      }
      String[] strs = null;
      ArrayList nameList = new ArrayList();
      for (int n = tmpList.size(); i < n; ++i) {
        strs = ((String)tmpList.get(i)).split(",");
        for (String str : strs) {
          nameList.add(pkNameMap.get(str));
        }
      }
      retMap.put(tmpFld, nameList);
    }
    return retMap;
  }
}